package com.match.input;

import java.math.BigDecimal;

import com.hazelcast.map.IMap;
import com.hazelcast.transaction.TransactionContext;
import com.hazelcast.transaction.TransactionOptions;
import com.lmax.disruptor.RingBuffer;
import com.match.common.model.dto.CancelOrderParam;
import com.match.common.model.dto.MatchOrder;
import com.match.plugin.disruptor.DisruptorPlugin;
import com.match.plugin.disruptor.producer.OrderProducer;
import com.match.plugin.hazelcast.HazelcastKit;
import com.match.plugin.hazelcast.HazelcastPlugin;
import com.match.plugin.kafka.Kafka;

import cn.hutool.json.JSONUtil;

/**
 * @ClassName: OrderData
 * @Description: TODO(订单数据请求)
 */
public class OrderData {

	static RingBuffer<MatchOrder> ringBuffer = DisruptorPlugin.ringBuffer;

	/**
	 * @Description: 
	 * TODO(接收委托订单数据，必须在同一个group中，保证分布式下线性撮合) 
	 * @return void 返回类型 
	 */
	public static void new_order(String matchOrderJson) {
		MatchOrder order = JSONUtil.toBean(matchOrderJson, MatchOrder.class);
		OrderProducer producer = new OrderProducer(ringBuffer);
		producer.onData(order);
	}

	/**
	 * @Description: TODO(接收撤销订单数据，不需要线性) 
	 * @return void 返回类型 
	 */
	public static void cancel_order(String cancelOrderJson) {
		CancelOrderParam cancel = JSONUtil.toBean(cancelOrderJson, CancelOrderParam.class);
		IMap<Long, MatchOrder> order_map = HazelcastPlugin.hazelcastInstance.getMap(HazelcastKit.getOrderBookKey(cancel.getCoinTeam(), cancel.getIsBuy()));
		if (order_map.containsKey(cancel.getId())) {
			TransactionOptions options = new TransactionOptions().setTransactionType(TransactionOptions.TransactionType.ONE_PHASE);
			TransactionContext context = HazelcastPlugin.hazelcastInstance.newTransactionContext(options);//事务支持
			context.beginTransaction();
			try {
				IMap<BigDecimal, BigDecimal> map = HazelcastPlugin.hazelcastInstance.getMap(HazelcastKit.getMatchKey(cancel.getCoinTeam(), cancel.getIsBuy()));
				MatchOrder cmo = order_map.remove(cancel.getId());
				map.compute(cmo.getPrice(), (k, v) -> v.subtract(cmo.getUnFinishNumber()));
				if (map.get(cmo.getPrice()).compareTo(BigDecimal.ZERO) > -1) {
					context.commitTransaction();
					Kafka.send(Kafka.revokeResult, Kafka.revokeResult, cmo.getId(), cmo);// 推送撤销成功结果
//						pushData.updateOrder(cmo); // 推送撤销成功结果
				} else {
					throw new Exception();
				}
			} catch (Exception e) {
				System.out.println("~~~撤销订单报错原型: "+cancelOrderJson+"，异常"+e.getMessage());
				context.rollbackTransaction();
			}
		}
	}
	
	
	
	
}
